package com.example.androidcomplete0102.ch16;

import com.example.androidcomplete0102.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class DlgQuestionFrg extends Activity implements QuestionDialogFragment.NoticeDialogListener {
	TextView tv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch16_dailogtest);
		tv = (TextView)findViewById(R.id.text);
		
	}
	
	public void mOnClick(View v){
		QuestionDialogFragment qFrg = new QuestionDialogFragment();
		Bundle bundle = new Bundle();
		bundle.putString("title", "질문");
		bundle.putString("msg", "어떤 연산을 하시겠습니까?");
		bundle.putString("Q1", "덧셈");
		bundle.putString("Q2", "곱셈");
		bundle.putInt("a", 3);
		bundle.putInt("b", 4);
		
		qFrg.setArguments(bundle);
		qFrg.show(getFragmentManager(), "dialog");
	}

	@Override
	public void onDialogClick(DialogFragment dialog, int res) {
		tv.setText("결과값은"+res);
	}
	
	
}

class QuestionDialogFragment extends DialogFragment{
	NoticeDialogListener mListener;
	Bundle bundle;
	//Fragment에서 Activity에게 값 전달
	public interface NoticeDialogListener{
		public void onDialogClick(DialogFragment dialog, int res);
		
	}
	
	@Override
	public void onAttach(Activity activity) {
		Log.d("DlgQuestionFrg","QuestionDialogFragment-onAttach()");
		super.onAttach(activity);
		try{
			mListener = (NoticeDialogListener) activity;
		}catch(ClassCastException e){
			throw new ClassCastException(activity.toString()+"NoticeDialogListener를 구형해야함");
		}
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		bundle = getArguments();
		return new AlertDialog.Builder(getActivity())
			.setTitle(bundle.getString("title"))
			.setIcon(R.drawable.ic_launcher)
			.setMessage(bundle.getString("msg"))
			.setPositiveButton(bundle.getString("Q1"), listener)
			.setNegativeButton(bundle.getString("Q2"), listener)
			.create();
	}	
	
	OnClickListener listener = new OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			int a = bundle.getInt("a");
			int b = bundle.getInt("b");
			switch(which){
			case DialogInterface.BUTTON_POSITIVE:
				mListener.onDialogClick(QuestionDialogFragment.this, a+b);
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				mListener.onDialogClick(QuestionDialogFragment.this, a*b);
				break;
			}
		}
	};
}